<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

class Offline extends Base
{
    /**
     * 学校码展示
     * @return mixed|\think\response\Json
     */
    public function schcode(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school'] = ['like', '%' . $params['school'] . '%'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['usetype'] = $params['type'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_schcode')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_schcode')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('time desc')
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 新建
     * @return mixed|\think\response\Json
     */
    public function activeAdd(){
        if(Request::instance()->isPost()){
            $active_name = input('active_name');
            $yearyear = input('yearyear');
            $gradegrade = input('gradegrade');
            $type = input('type');
            $sexsex = input('sexsex');
            $insert = [
                'school' => $active_name,
                'yearyear' => $yearyear,
                'gradegrade' => $gradegrade,
                'sexsex' => $sexsex,
                'usetype' => $type,
                'time' => date('Y-m-d H:i:s')
            ];
            if($type >= 2){
                $active_member_num = round(input('active_member_num'),2);
                $insert['money'] = $active_member_num;
            }
            Db::startTrans();
            try{
                $res = Db::table('up_offline_schcode')->insertGetId($insert);
                $ercode = $this->scerweima($res);
                Db::table('up_offline_schcode')->where('id',$res)->setField('ercode',$ercode);
                Db::commit();
                return json(['code' => 200, 'msg' => '新建成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '新建失败']);
            }
        }
        return $this->fetch('offline/activeadd');
    }
    function scerweima($aid){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        require_once VENDOR_PATH . "phpqrcode.php";
        $rand = date('YmdHis').rand(100000,999999);
        $value = "$url/index/Index/index?schcodeid=$aid"; //二维码内容：链接
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 8;           //生成图片大小
        //生成二维码图片
        $ymd = date('Ymd');
        $zip_path = "{$dir}/uploads/face/$ymd";
        if (!file_exists($zip_path)) {
            mkdir($zip_path);
        }
        $filename = "$zip_path/{$rand}.png";
        $filehttp = "{$url}/uploads/face/$ymd/{$rand}.png";
        \QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = $filename;              //已经生成的原始二维码图片文件
        $QR = imagecreatefromstring(file_get_contents($QR));
        //输出图片
//        imagepng($QR, 'qrcode.png');
        imagedestroy($QR);
        return $filehttp;
    }
    
    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function activeEdit(){
        $active_id = input('id');
        if(Request::instance()->isPost()){
            $active_name = input('active_name');
            $type = input('type');
            $yearyear = input('yearyear');
            $gradegrade = input('gradegrade');
            $sexsex = input('sexsex');
            $update = [
                'school' => $active_name,
                'yearyear' => $yearyear,
                'gradegrade' => $gradegrade,
                'sexsex' => $sexsex,
                'time' => date('Y-m-d H:i:s')
            ];
            if($type >= 2){
                $active_member_num = round(input('active_member_num'),2);
                $update['money'] = $active_member_num;
            }
            $res = Db::table('up_offline_schcode')->where('id', $active_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        
        $info = Db::table('up_offline_schcode')
            ->where('id', $active_id)
            ->find();
        $this->assign([
            'id' => $active_id,
            'info' => $info
        ]);
        return $this->fetch('offline/activeedit');
    }
    /**
     * 改状态（是否开启）
     * @author
     */
    public function changeStatus()
    {
        extract(input());
        $res = Db::table('up_offline_schcode')
            ->where('id',$id)
            ->update([
                'time' => date('Y-m-d H:i:s'),
                'status' => $num
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function activeDel(){
        $active_id = input('id');
        $res = Db::table('up_offline_schcode')->where('id', $active_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }

    /**
     * 订单
     * @return mixed|\think\response\Json
     */
    public function order(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];

            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school|orderno|name|idcard|backno|phone'] = ['like', '%' . $params['school'] . '%'];
            }
            // 状态
            if(isset($params['o_status']) && $params['o_status'] != ''){
                $where['status'] = $params['o_status'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['fromtype'] = $params['type'];
            }
            if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']=="")
            {
                $where['time'] = ['>= time',$params['start']];
            }
            if(isset($params['end'])&&$params['end']!=""&&isset($params['start'])&&$params['start']=="")
            {
                $where['time'] = ['<= time',$params['end']];
            }
            if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']!="")
            {
                $where['time'] = ['between time',[$params['start'],$params['end']]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_order')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_order')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function orderdel(){
        $active_id = input('id');
        $res = Db::table('up_offline_order')->where('id', $active_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 审核
     * @return mixed|\think\response\Json
     */
    public function shenhe(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            $where['yes'] = 1;
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school'] = ['like', '%' . $params['school'] . '%'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['usetype'] = $params['type'];
            }

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_schcode')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_schcode')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('time desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 同意
     * @return \think\response\Json
     */
    public function yesyes(){
        $active_id = input('id');
        $res = Db::table('up_offline_schcode')->where('id', $active_id)->setField('yes',2);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败，请重试']);
        }
    }
    /**
     * 同意
     * @return \think\response\Json
     */
    public function nono(){
        $active_id = input('id');
        $res = Db::table('up_offline_schcode')->where('id', $active_id)->setField('yes',3);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败，请重试']);
        }
    }
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function excelwater(){
        set_time_limit(0);
        $params = input('param.');
        $where = [];
        // 活动名称
        if(isset($params['school']) && $params['school'] != ''){
            $where['school|orderno|name|idcard|backno'] = ['like', '%' . $params['school'] . '%'];
        }
        // 状态
        if(isset($params['o_status']) && $params['o_status'] != ''){
            $where['status'] = $params['o_status'];
        }
        if(isset($params['type']) && $params['type'] != ''){
            $where['fromtype'] = $params['type'];
        }
        if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']=="")
        {
            $where['time'] = ['>= time',$params['start']];
        }
        if(isset($params['end'])&&$params['end']!=""&&isset($params['start'])&&$params['start']=="")
        {
            $where['time'] = ['<= time',$params['end']];
        }
        if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']!="")
        {
            $where['time'] = ['between time',[$params['start'],$params['end']]];
        }
        $field = [
            'orderno','backno','school','grade','class','name','sex','idcard',
            'height','weight','size','sw_j','sw_x',
            'sw_y','sw_t','sw_b','sw_k','xiguan',
            'phone', 'fromtype','type','status','money',
            'time','send_name','send_address'
        ];
        $data = Db::name('offline_order')
            ->where($where)
            ->field($field)
            ->order('time desc')
            ->select();
        if($data){
            $cellname = [
                '订单号', '支付流水号', '学校', '年级', '班级', '学生姓名', '学生性别', '入学年份',
                '身高', '体重', '衣服尺码', '三围/肩宽', '三围/胸围',
                '三围/腰围', '三围/臀围', '三围/臂长', '三围/裤长', '穿衣习惯',
                '注册手机', '记录类型', '支付类型', '订单状态', '支付金额',
                '支付时间','收件人','收件地址'
            ];
            $status = ['status','fromtype','type'];
            $values = [
                'status' => ['1' => '未支付','2' => '已支付'],
                'fromtype' => ['1' => '仅收集','2' => '仅支付','3' => '收集兼支付'],
                'type' => ['1' => '微信','2' => '支付宝']
            ];
            $res = exportExcel('payonline',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}